<template>
	<view>
		<view class="index-box">
			<!--  规则按钮-->
			<view @click="$linkTo(`/package/activity/turntable/role?id=${activeId}`)" class="rule-btn l1 flex-ct">活动规则</view>
			<view class="outer-wrap">
				<view class="outer">
					<view class="son_box">
						<view class="circle-1" :animation="animationData">
							<view :class="['circle-2', degList[index]]" v-for="(item, index) in prizeList" :key="index">
								<view class="circle-m">
									<view :class="['circle-text', index % 2 === 1 ? 'c-70' : '']">{{ item.name }}</view>
									<image :src="item.logo || logo"></image>
								</view>
							</view>
						</view>
						<view class="pointer" @click="turnStart"></view>
					</view>
				</view>
			</view>
			<!--  剩余机会-->
			<view class="times">你剩余{{ total }}次抽奖机会</view>
			<view class="sub-btn" @click="seeMyprize">我的奖品</view>
			<!--  抽奖结果-->
			<view class="result-wrap flex-csb-a">
				<view class="result-icon"><image src="../static/ic_2.png"></image></view>
				<view class="result-list-wrap">
					<view class="ri-title">中奖名单</view>
					<swiper
						v-if="dataList.length > 0"
						@touchmove="stopMove"
						@change="recordChange"
						class="result-list"
						vertical
						circular
						:display-multiple-items="dataList.length < 5 ? dataList.length : 5"
						:autoplay="true"
						:interval="1000"
					>
						<swiper-item class="result-item" v-for="(item, index) in dataList" :key="index">
							<view class="recor_item">
								<view class="ri-text one-row-hide">{{ item.nickname }} 获得</view>
								<view class="ri-text one-row-hide">{{ item.name }}</view>
							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</view>
		<express-view v-model="popupVisible" :orderId="orderId" @submitFinsh="$initPage"></express-view>
		<sww-login></sww-login>
	</view>
</template>

<script>
import { isBefore, isAfter, formatDate } from '@/utils/moment/index.js';
import { pagingMixin } from '@/mixins/pagingMixin.js';
import { pageShare } from '@/mixins/pageShare.js';
import expressView from './components/express.vue';
export default {
	mixins: [pagingMixin, pageShare],
	components: {
		'express-view': expressView
	},
	data() {
		return {
			logo: 'http://klwl-file.oss-cn-shenzhen.aliyuncs.com/202106/jhstest/46687951711100.gif',
			animationData: '',
			animation: null,
			degList: ['', 't-45', 't-90', 't-135', 't-180', 't-225', 't-270', 't-315'], // 用于调整角度
			stopTouch: false, // 是否禁用点击
			total: 0, // 剩余抽奖次数
			prizeNum: 0, // 总得奖品数量
			prizeObj: {}, // 当前抽中的奖
			prizeList: [], //奖品列表
			dataList: [], //中将名单
			clearForm: '', // 提交的个人信息
			popupVisible: false, // 弹窗提交信息
			orderId: '',
			activeInfo: {}, //活动详情信息
			activeId: '', //活动ID
			duration: 5000 // 转多久
		};
	},
	onLoad(options) {
		// let date = new Date();
		// let old = '2021-07-29 17:15:00'
		// let bol = isBefore(old, date, 'YYYY-MM-DD HH:mm:ss','YYYY-MM-DD')
		// console.log('bol',bol)
		if (options && options.id) {
			this.activeId = options.id;
			this.$initPage();
			this.getRecordList();
		}
	},
	onReady: function() {
		this.animation = wx.createAnimation({
			timingFunction: 'ease-out',
			duration: this.duration
		});
	},
	onShareAppMessage: function() {
		return this.getShareAppMessage();
	},
	// 微信小程序分享(朋友圈)
	onShareTimeline: function() {
		return this.getShareTimeline();
	},
	methods: {
		$initPage() {
			this.getProdList();
			this.getActieInfo();
		},
		getActieInfo() {
			this.$loading();
			this.$resPost('GetGameInfo', { pk_id: this.activeId }).then(({ data }) => {
				this.activeInfo = data;
				if (data.order_num > 0) {
					this.total = 0;
				} else if (data.num) {
					this.total = data.num - data.record_num > 0 ? data.num - data.record_num : 0;
				}
				this.$hide();
			});
		},
		getProdList() {
			this.$resPost('GetGameProductList', { type: this.activeId, page_size: 8 }).then(({ data }) => {
				this.prizeList = this.formatData(data);
			});
		},
		//初始化中奖几率
		formatData(list) {
			// let frequency = parseInt(list[0].frequency || -2);
			// let { total } = this;
			let prizeNum = 0; // 总的奖品数量 包含谢谢惠顾
			let arr = list.map(item => {
				item.num = item.num ? parseInt(item.num) : 0;
				item = {
					...item,
					start: prizeNum,
					end: prizeNum + item.num,
					notPrize: item.name.indexOf('谢谢') > -1 //true代表谢谢惠顾
				};
				prizeNum += item.num;
				return item;
			});
			//可抽奖次数
			// total = total - frequency;
			this.prizeNum = prizeNum;
			// this.total = total > 0 ? total : 0;
			return arr;
		},
		stopMove() {
			return false;
		},
		// 开始抽奖
		turnStart() {
			this.$login('$initPage').then(() => {
				//验证时间
				if (!this.checkTimes()) return;
				if (this.total > 0) {
					this.$loading();
					let { prizeList, prizeNum } = this;
					// 获取奖品对象
					let num = Math.floor(Math.random() * prizeNum);
					let index = prizeList.findIndex(item => num >= item.start && num < item.end);
					let prizeObj = prizeList[index];
					if (index > -1) {	
						//向后台写入/验证奖品信息
						this.$resPost('AddGameOrder', {
							pro_id: prizeObj.pk_id,
							remark: prizeObj.name,
							pk_id: this.activeId
						})
							.then(res => {
								if (!res.data.order_id) {
									this.$toast('系统出错了');
									return;
								}
								// 获取后台返回奖品ID，有可能中奖了，没有库存，后台返回谢谢惠顾产品DI
								index = prizeList.findIndex(item => item.pk_id == res.data.pro_id);
								if (index > -1) {
									this.orderId = res.data.order_id;
									this.$hide();
									this.run(index + 1, prizeList[index]);
								} else {
									this.$toast('系统出错了');
								}
								this.$hide();
							})
							.catch(() => {
								this.$toast('系统出错了');
							});
					} else {
						this.$toast('系统出错了');
					}
				} else {
					this.$toast('您没有抽奖次数了~');
				}
			});
		},
		//验证时间
		checkTimes() {
			let date = new Date();
			let { activeInfo } = this;
			//验证是否在活动日期期间
			if (isBefore(activeInfo.start_date, date, 'YYYY/MM/DD HH:mm:ss') && isAfter(activeInfo.end_date, date, 'YYYY/MM/DD HH:mm:ss')) {
				//验证是否在活动时间段内
				let dateStr = formatDate(date);
				let times = activeInfo.time.split('-');
				if (isBefore(`${dateStr} ${times[0]}`, date, 'YYYY-MM-DD HH:mm') && isAfter(`${dateStr} ${times[1]}`, date, 'YYYY-MM-DD HH:mm')) {
					return true;
				} else {
					this.showActiveMsg(times[0], times[1]);
					return false;
				}
			} else {
				this.showActiveMsg(activeInfo.start_date, activeInfo.end_date);
				return false;
			}
		},
		// 开启动画
		run(prizeIndex, prizeObj) {
			let that = this;
			let { stopTouch, total } = that;
			if (!stopTouch) {
				this.stopTouch = true;
				this.prizeObj = prizeObj;
				this.total = this.total - 1;

				let turnDeg = 360 - Math.floor(Math.random() * 45) - (prizeIndex - 1) * 45;
				let endDeg = 360 - turnDeg;
				let deg = 360 * 4 + turnDeg;
				that.animation.rotate(deg).step();
				this.animationData = this.animation.export();

				that.turnTimeout = setTimeout(
					function() {
						that.animation.rotate(-endDeg).step({
							timingFunction: 'step-end',
							duration: 10
						});
						this.animationData = that.animation.export();
						this.stopTouch = false;
						if (!prizeObj.notPrize) {
							// 中奖了
							if (prizeObj.mode == '1') {
								// 邮寄
								this.$toast(`恭喜您获得 {${prizeObj.name}},请完善个人信息，我们会及时发货~`);
								this.popupVisible = true;
							} else if (prizeObj.mode == '4') {
								//自提
								uni.showModal({
									title: '恭喜中奖',
									content: '请阅读活动规则，到指定自提地点领取奖品~',
									showCancel: false,
									confirmText: '我知道了'
								});
							} else {
								// 充值领取
								uni.showModal({
									title: '恭喜中奖',
									content: '充值领取',
									showCancel: false,
									confirmText: '我知道了'
								});
							}
						}
					}.bind(that),
					this.duration
				);
			}
		},
		//未在活动时间
		showActiveMsg(start = '', end = '') {
			uni.showModal({
				title: '活动时间',
				content: `${start} - ${end}`,
				showCancel: false,
				confirmText: '我知道了'
			});
		},
		// 查看我的奖品
		seeMyprize() {
			this.$login('seeMyprize').then(() => {
				this.$linkTo(`/package/activity/turntable/prize?id=${this.activeId}`);
			});
		},
		// 获取中奖记录
		getRecordList() {
			this._init_data('GetGameOrderList', { pk_id: this.activeId, users_id: null });
		},
		recordChange(e) {
			let index = e.detail.current;
			if (index > this.dataList.length - 4 && !this.dataListParams.loading) {
				this._load_data();
			}
		}
	}
};
</script>
<style>
page {
	background-color: #f5f5f5;
	height: 100%;
}
</style>
<style scoped lang="scss">
@import './turntable';
</style>
